import {
  _decorator,
  Component,
  Node,
  Sprite,
  SpriteFrame,
  SpriteAtlas,
  tween,
  Vec3,
} from "cc";
import { Card } from "./Card";
const { ccclass, property } = _decorator;

@ccclass("CardManager")
export class CardManager extends Component {
  @property(Node) frontNode: Node = null;
  @property(Node) backNode: Node = null; // 牌堆
  private showingFront: boolean = false;

  hide() {
    this.node.active = false;
    this.frontNode.active = false;
    this.backNode.active = false;
  }

  /**
   * 显示卡片的正面
   */
  showFront() {
    this.node.active = true;
    this.showingFront = true;
    this.frontNode.active = true;
    this.backNode.active = false;
  }

  /**
   * 显示卡片的背面
   */
  showBack() {
    this.node.active = true;
    this.showingFront = false;
    this.frontNode.active = false;
    this.backNode.active = true;
  }

  /**
   * 设置卡牌图像
   *
   * @param card 卡牌对象
   */
  setCard(card: Card) {
    const sprite = this.frontNode.getComponent(Sprite);
    if (!sprite) {
      console.error("Sprite component not found on frontNode");
      return;
    }

    const frame = sprite.spriteAtlas.getSpriteFrame(card.code);

    if (!frame) {
      console.error("SpriteFrame not found for code:", card.code);
      return;
    }

    sprite.spriteFrame = frame;
  }

  /**
   * 翻转到正面
   */
  flipToFront(): Promise<void> {
    if (this.showingFront) return Promise.resolve(); // 已经在正面就立即返回

    this.showingFront = true;

    return new Promise((resolve) => {
      tween(this.node)
        .to(0.15, { scale: new Vec3(0, 1, 1) }) // 收缩 X
        .call(() => {
          this.showFront();
        })
        .to(0.15, { scale: new Vec3(1, 1, 1) }) // 展开 X
        .call(() => {
          resolve(); // 动画完成，Promise resolve
        })
        .start();
    });
  }

  /**
   * 翻转到背面
   */
  flipToBack(): Promise<void> {
    if (!this.showingFront) return Promise.resolve(); // 已经是背面，直接 resolve

    this.showingFront = false;

    return new Promise((resolve) => {
      tween(this.node)
        .to(0.15, { scale: new Vec3(0, 1, 1) }) // 收缩
        .call(() => {
          this.showBack();
        })
        .to(0.15, { scale: new Vec3(1, 1, 1) }) // 展开
        .call(() => {
          resolve(); // 翻转完成
        })
        .start();
    });
  }
}
